<?php

namespace app\admin\controller;

use app\common\helper\MyHelper;

use think\Db;

use app\common\service\SysLogService;

class Modelextraction extends Common
{

    private $insertArr;

    public function saveOrUptTemplate()
    {

        $data = request()->put();

        $qzh = "FZ02";
        $id = $data['id'];

        $list = array();
        $list ['is_delete'] = 0;
        $template_name = $data['template_name'];
        $priority = $data['priority'];
        $mode = $data['mode'];
        $status = $data['status'];

        // 检验 identifying_features

        $identifyingFeaturesData = $data['identifying_features'];

        if (empty($identifyingFeaturesData)) {
            return json(array("code" => 400, "data" => array(), "message" => "identifying_features不能为空"));
        }

        foreach ($identifyingFeaturesData as $key => $value) {
            if (empty($value)) {
                return json(array("code" => 400, "data" => array(), "message" => "判定特征有数据未填写"));

            }
            $fordata = $value['value'];
            foreach ($fordata as $k => $v) {
                if (empty($v['titleOrContent'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "标题或者内容未填写"));
                }
                if (empty($v['value'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "正则未填写"));
                }
            }
        }


        $list['template_name'] = $template_name;
        $list['priority'] = $priority;
        $list['mode'] = $mode;
        $list['status'] = $status;
        $list['identifying_features'] = json_encode($identifyingFeaturesData, JSON_UNESCAPED_UNICODE);
        $list['article_id'] = $data['article_id'];
        $list['persondesc'] = $data['persondesc'];

        $cueWord = $data['persondesc'];
        $article_id = $data['article_id'];

//        var_dump($cueWord);

        //跑模型出数据具
        //查出文章内容


        $articleResult = MyHelper::getArticleInfoById($article_id);

        $content = $articleResult['data']['content'];

        $cueWord = $cueWord . "一下是文章正文：
          $content 
        ";

//
        $data = $this->ollama($cueWord);


//
        $dataArr = json_decode($data, true);

//        var_dump($dataArr);


        $Json = $dataArr['message']['content'];


        $Json = getJson($Json);


        $data = json_decode($Json, true);



        $this->jsonSplitting($data, $qzh);




        if (empty($id)) {
            // 添加
            $list['create_time'] = date("Y-m-d H:i:s");
            $result = Db::table("zstp_template")->insert($list);
            if ($result) {
                return json(array("code" => 200, "data" => $result, "message" => "添加成功"));
            } else {
                return json(array("code" => 400, "data" => $result, "message" => "添加失败"));
            }

        } else {
            //更新
            $list['update_time'] = date("Y-m-d H:i:s");
            $result = Db::table("zstp_template")->where(array("id" => $id))->update($list);

            return json(array("code" => 200, "data" => $result, "message" => "保存成功"));

        }


    }
    /*
     * 值保存不跑大模型
     */
    public function saveTemplate()
    {

        $data = request()->put();

        $id = $data['id'];

        $list = array();
        $list ['is_delete'] = 0;
        $template_name = $data['template_name'];
        $priority = $data['priority'];
        $mode = $data['mode'];
        $status = $data['status'];

        // 检验 identifying_features

        $identifyingFeaturesData = $data['identifying_features'];

        if (empty($identifyingFeaturesData)) {
            return json(array("code" => 400, "data" => array(), "message" => "identifying_features不能为空"));
        }

        foreach ($identifyingFeaturesData as $key => $value) {
            if (empty($value)) {
                return json(array("code" => 400, "data" => array(), "message" => "判定特征有数据未填写"));

            }
            $fordata = $value['value'];
            foreach ($fordata as $k => $v) {
                if (empty($v['titleOrContent'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "标题或者内容未填写"));
                }
                if (empty($v['value'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "正则未填写"));
                }
            }
        }


        $list['template_name'] = $template_name;
        $list['priority'] = $priority;
        $list['mode'] = $mode;
        $list['status'] = $status;
        $list['identifying_features'] = json_encode($identifyingFeaturesData, JSON_UNESCAPED_UNICODE);

        if(!empty($data['article_id'])){
            $list['article_id'] = $data['article_id'];
        }


        $list['persondesc'] = $data['persondesc'];
        




        if (empty($id)) {
            // 添加
            $list['create_time'] = date("Y-m-d H:i:s");
            $id = Db::table("zstp_template")->insertGetId($list);
            if ( $id) {
                $sysLogService = new SysLogService();
                $result =  $sysLogService->addLog('添加模板('. $template_name.')', $id, 1, '添加模板id:'.$id);
                return json(array("code" => 200, "data" => $id, "message" => "添加成功"));
            } else {
                return json(array("code" => 400, "data" => $id, "message" => "添加失败"));
            }

        } else {
            //更新
            $list['update_time'] = date("Y-m-d H:i:s");
        
            $sysLogService = new SysLogService();
            $listJson = json_encode($list, JSON_UNESCAPED_UNICODE);
            $result =  $sysLogService->addLog('更新模板('. $template_name.')', $id, 2, "更新的内容:({$listJson})");


            $result = Db::table("zstp_template")->where(array("id" => $id))->update($list);

            return json(array("code" => 200, "data" => $result, "message" => "保存成功"));

        }


    }

    function jsonSplitting($data, $qzh)
    {
        //人的属性
        if (!empty($data['personnel'])) {

            $personnelList = $data['personnel'];

            foreach ($personnelList as $key => $value) {

                $this->insertArr = [];
                $this->insertArr['qzh'] = $qzh;
                if (!empty($value['name'])) {
                    $res = checkFields($value['name']);
                    if (!$res) {
                        continue;
                    }
                    $name = $res;
                    $this->insertArr['name'] = $name;
                }


                $this->fieldAssignment($value['gender'], "gender");
                $this->fieldAssignment($value['age'], "age");
                $this->fieldAssignment($value['ethnicity'], "ethnicity");
                $this->fieldAssignment($value['political_status'], "political_status");
                $this->fieldAssignment($value['marital_status'], "marital_status");
                $this->fieldAssignment($value['spouse'], "spouse");
                $this->fieldAssignment($value['organization'], "organization");
                $this->fieldAssignment($value['position'], "position");
                $this->fieldAssignment($value['birth_date'], "birth_date");
                $this->fieldAssignment($value['party_join_date'], "party_join_date");
                $this->fieldAssignment($value['phone_number'], "phone_number");
                $this->fieldAssignment($value['military_rank'], "military_rank");

                $mapPerson['name'] = $name;
                $mapPerson['qzh'] = $qzh;
                $result = Db::table("zstp_neo4j_personal_attributes")->insert($this->insertArr);
//                $result = Db::table("zstp_neo4j_personal_attributes")->where($mapPerson)->find();
//                if (empty($result)) {
//                    $result = Db::table("zstp_neo4j_personal_attributes")->insert($this->insertArr);
//                }


            }

        }
        if (!empty($data['event'])) {
            $eventList = $data['event'];

            $isSingle = true;
            foreach ($eventList as $key => $value) {
                $this->insertArr = [];
                $this->insertArr['qzh'] = $qzh;
                //判断 是否是多人或者多组织模版
                if ($key == 0) {
                    if (isset($value['event_subject'])) {
                        $isSingle = false;
                    }
                }

                if ($isSingle) {
                    $this->eventSingle($value);
                    $mapPerson['name'] = $name;
                    $mapPerson['qzh'] = $qzh;
                    $result = Db::table("zstp_neo4j_event")->where($mapPerson)->find();
//                    if (empty($result)) {
                    $result = Db::table("zstp_neo4j_event")->insert($this->insertArr);
//                    }

                } else {
                    $this->eventMulti($value, $qzh);
                }


            }

        }


    }

    function eventMulti($value, $qzh)
    {

        $eventSubjectList = $value['event_subject'];

        foreach ($eventSubjectList as $key => $v) {
            $this->fieldAssignment($v, "name");
            $this->fieldAssignment($value['event_type'], "event_type");
            $this->fieldAssignment($value['reason'], "reason");
//            if (!empty($value['summary'])) {
                $this->fieldAssignment($value['name'], "summary");
//            }

            $this->fieldAssignment($value['issuer'], "issuer");
            $this->fieldAssignment($value['date'], "date");

            $mapPerson['name'] = $v;
            $mapPerson['qzh'] = $qzh;
            $result = Db::table("zstp_neo4j_event")->where($mapPerson)->find();
            $result = Db::table("zstp_neo4j_event")->insert($this->insertArr);
//            if (empty($result)) {
//                $result = Db::table("zstp_neo4j_event")->insert($this->insertArr);
//            }


        }


    }

    function eventSingle($value)
    {

        $this->fieldAssignment($value['name'], "name");
        $this->fieldAssignment($value['event_type'], "event_type");

        if (!empty($value['summary'])) {
            $this->fieldAssignment($value['summary'], "summary");
        }


        $this->fieldAssignment($value['reason'], "reason");
        $this->fieldAssignment($value['issuer'], "issuer");
        $this->fieldAssignment($value['date'], "date");

    }

    function fieldAssignment($str, $fieldName)
    {

        if (!empty($str)) {
            $res = checkFields($str);
            if ($res != false) {
                $this->insertArr[$fieldName] = $res;
            }
        }

    }

    function ollama($cueWord)
    {

        $ch = curl_init();

        $ollamaURL = config("ollamaURL");

        $url = "{$ollamaURL}/api/chat";


        $headers = [
            'Authorization: Bearer sk-tiuvcznrtvpmjnipckrwiaotbspbpeslgbxadpwznrfdqocc',
            'Content-Type: application/json'
        ];
        $data = json_encode([
            "model" => "qwen2.5:7b",
            "options" => ["num_ctx" => 8192],
            "messages" => [
                [
                    "role" => "system",
                    "content" => ""
                ],
                [
                    "role" => "user",
                    "content" => $cueWord,
                ]
            ],
            "stream" => false,
            "max_tokens" => 512,
            "stop" => ["<string>"],
            "temperature" => 0.7,
            "top_p" => 0.7,
            "top_k" => 50,
            "frequency_penalty" => 0.5,
            "n" => 1,
            "response_format" => ["type" => "json_object"]
        ]);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// 执行请求并获取响应
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        } else {
            // 输出响应结果
//            echo $response;
        }

// 关闭cURL资源
        curl_close($ch);


        return $response;

    }


    function Json2()
    {

        return '{
  "personnel": [
    {
      "name": "郝树立",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "亳州市人民医院",
      "position": "党委副书记、院长",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "贾其彬",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "中煤新集利辛发电有限公司",
      "position": "热控班长",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "耿芳",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "涡阳县总工会",
      "position": "党组成员、副主席",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "张飞国",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "(亳州)有限公司",
      "position": "焊工班组长",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "张永建",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "亳州市谯城阳光电力维修工程有限责任公司",
      "position": "项目经理",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "陈建国",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽金不换白酒集团",
      "position": "销售员",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "蒋丽",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "亳州中药有限公司",
      "position": "验收员",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "王庆帅",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "中煤新集利辛矿业有限公司固定队",
      "position": "电工班班长",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "许飞",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "亳州工业学校第一党支部",
      "position": "智能制造部主任",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "朱钰乐",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "亳州市公安局技侦支队一大队",
      "position": "大队长",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "刘可蒙",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽河面业有限责任公司",
      "position": "调度员",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "张勇",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽春雨汽车集团",
      "position": "汽车维修质检员",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "陈景民",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽禾丰浩翔农业发展有限公司",
      "position": "育种总监",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "王喜英",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽济人药业股份有限公司固体制剂车间",
      "position": "技术指导员",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "曹卫卫",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽雷允上药业有限公司",
      "position": "生产经理",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "荣振利",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "安徽省东昕食品有限公司",
      "position": "技术中心主任",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "罗龙",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "涡阳县鸿路建材有限公司",
      "position": "总经理",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    },
    {
      "name": "刘振伯",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "unknown",
      "organization": "希和户外运动集团股份有限公司",
      "position": "董事长",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "unknown"
    }
  ],
  "event": [
    {
      "event_type": "奖励",
      "name": "安徽省五一劳动奖状",
      "event_subject": ["亳州市公共交通集团有限公司", "安徽正宇面粉有限公司"],
      "reason": "unknown",
      "issuer": "安徽省总工会",
      "date": "2025-04-01"
    },
    {
      "event_type": "奖励",
      "name": "安徽省五一劳动奖章",
      "event_subject": ["郝树立", "贾其彬", "耿芳", "张飞国", "张永建", "陈建国", "蒋丽", "王庆帅", "许飞", "朱钰乐", "刘可蒙", "张勇", "陈景民", "王喜英", "曹卫卫", "荣振利", "罗龙", "刘振伯"],
      "reason": "unknown",
      "issuer": "安徽省总工会",
      "date": "2025-04-01"
    }
  ]
}
';

    }


    function Json()
    {

        return '{
  "personnel": [
    {
      "name": "谢益斌",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "少校"
    },
    {
      "name": "王程杰",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "少校"
    },
    {
      "name": "张洪波",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "上尉"
    },
    {
      "name": "肖盈盈",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "上尉"
    },
    {
      "name": "朱晓茸",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "上尉"
    },
    {
      "name": "陆海荣",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "上尉"
    },
    {
      "name": "邱建军",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "中校"
    },
    {
      "name": "徐丹丹",
      "gender": "unknown",
      "age": "unknown",
      "ethnicity": "unknown",
      "political_status": "unknown",
      "marital_status": "unknown",
      "spouse": "none",
      "organization": "部队",
      "position": "未知",
      "birth_date": "unknown",
      "party_join_date": "unknown",
      "phone_number": "unknown",
      "military_rank": "中校"
    }
  ],
  "event": [
    {
      "event_type": "军衔晋升",
      "name": "谢益斌",
      "summary": "从少校晋升为中校",
      "reason": "职务晋升",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "王程杰",
      "summary": "从少校晋升为中校",
      "reason": "职务晋升",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "张洪波",
      "summary": "从上尉晋升为少校",
      "reason": "未知",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "肖盈盈",
      "summary": "从上尉晋升为少校",
      "reason": "未知",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "朱晓茸",
      "summary": "从上尉晋升为少校",
      "reason": "未知",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "陆海荣",
      "summary": "从上尉晋升为少校",
      "reason": "未知",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "邱建军",
      "summary": "从中校晋升为上校",
      "reason": "未知",
      "issuer": "部队首长",
      "date": "2025-04-03"
    },
    {
      "event_type": "军衔晋升",
      "name": "徐丹丹",
      "summary": "从中校晋升为上校",
      "reason": "未知",
      "issuer": "部队首长",
      "date": "2025-04-03"
    }
  ]
}';
    }


}
